﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MinesweeperGame
{
    public partial class Form1 : Form
    {
        private GameEngine gameEngine;
        private AutoDemo autoDemo;
        private Statistics statistics;
        private Leaderboard leaderboard;
        private Button[,] cellButtons;
        private const int CELL_SIZE = 30;
        private const int GRID_MARGIN = 10;
        
        // 鼠标按键状态跟踪
        private bool leftMouseDown = false;
        private bool rightMouseDown = false;
        private Point lastMousePosition;
        
        // 旗帜字符
        private const string FLAG_CHAR = "🚩";
        
        // 虚拟鼠标相关
        private PictureBox virtualMouseCursor;
        private Point virtualMousePosition;
        private bool isVirtualMouseVisible = false;
        private Timer virtualMouseTimer;
        private Point targetPosition;
        private bool isMoving = false;
        
        // 虚拟鼠标按钮状态
        private bool virtualLeftButtonDown = false;
        private bool virtualRightButtonDown = false;
        private Image originalCursorImage;

        public Form1()
        {
            InitializeComponent();
            InitializeGame();
        }

        /// <summary>
        /// 初始化游戏
        /// </summary>
        private void InitializeGame()
        {
            
            // 创建游戏引擎
            gameEngine = new GameEngine();
            
            // 创建自动演示
            autoDemo = new AutoDemo(gameEngine);
            
            // 创建统计管理器
            statistics = new Statistics();
            
            // 创建排行榜管理器
            leaderboard = new Leaderboard();
            
            // 订阅事件
            gameEngine.GameStateChanged += OnGameStateChanged;
            gameEngine.CellChanged += OnCellChanged;
            autoDemo.OperationCompleted += OnDemoOperationCompleted;
            autoDemo.DemoCompleted += OnDemoCompleted;

            // 初始化界面
            InitializeUI();
            
            // 开始新游戏
            StartNewGame();
        }

        /// <summary>
        /// 初始化用户界面
        /// </summary>
        private void InitializeUI()
        {
            // 绑定事件
            newGameButton.Click += NewGameButton_Click;
            difficultyComboBox.SelectedIndexChanged += DifficultyComboBox_SelectedIndexChanged;
            gameTimer.Tick += GameTimer_Tick;
            autoDemoCheckBox.CheckedChanged += AutoDemoCheckBox_CheckedChanged;
            startDemoButton.Click += StartDemoButton_Click;
            pauseDemoButton.Click += PauseDemoButton_Click;
            stopDemoButton.Click += StopDemoButton_Click;
            stepDemoButton.Click += StepDemoButton_Click;
            demoSpeedComboBox.SelectedIndexChanged += DemoSpeedComboBox_SelectedIndexChanged;
            statsButton.Click += StatsButton_Click;
            resetStatsButton.Click += ResetStatsButton_Click;
            faceButton.Click += FaceButton_Click;
            leaderboardButton.Click += LeaderboardButton_Click;

            // 设置默认值
            difficultyComboBox.SelectedIndex = 0;
            demoSpeedComboBox.SelectedIndex = 1;

            // 初始化演示控制按钮状态
            UpdateDemoControls();
            
            // 创建状态预览按钮
            CreatePreviewButtons();
            
            // 初始化虚拟鼠标
            InitializeVirtualMouse();
            
            // 添加窗体大小改变事件
            this.Resize += Form1_Resize;
        }

        /// <summary>
        /// 开始新游戏
        /// </summary>
        private void StartNewGame()
        {
            // 停止演示
            if (autoDemo.IsRunning)
            {
                autoDemo.StopDemo();
            }

            // 停止计时器
            gameTimer.Stop();

            // 获取选择的难度
            Difficulty difficulty = (Difficulty)difficultyComboBox.SelectedIndex;
            
            // 记录游戏开始
            statistics.RecordGameStarted(difficulty);
            
            // 初始化游戏
            gameEngine.InitializeGame(difficulty);
            
            // 创建游戏网格
            CreateGameGrid();
            
            // 更新界面
            UpdateUI();
        }

        /// <summary>
        /// 创建游戏网格
        /// </summary>
        private void CreateGameGrid()
        {
            // 暂时禁用界面更新以提高性能
            gamePanel.SuspendLayout();
            this.SuspendLayout();

            try
            {
                // 快速清除现有的按钮
                if (cellButtons != null)
                {
                    // 保存虚拟鼠标光标（如果存在）
                    PictureBox savedVirtualMouse = null;
                    if (virtualMouseCursor != null && gamePanel.Controls.Contains(virtualMouseCursor))
                    {
                        savedVirtualMouse = virtualMouseCursor;
                        gamePanel.Controls.Remove(virtualMouseCursor);
                    }
                    
                    // 批量清除所有控件
                    gamePanel.Controls.Clear();
                    
                    // 恢复虚拟鼠标光标
                    if (savedVirtualMouse != null)
                    {
                        gamePanel.Controls.Add(savedVirtualMouse);
                        savedVirtualMouse.BringToFront();
                    }
                    
                    // 批量释放按钮资源
                    for (int row = 0; row < cellButtons.GetLength(0); row++)
                    {
                        for (int col = 0; col < cellButtons.GetLength(1); col++)
                        {
                            if (cellButtons[row, col] != null)
                            {
                                cellButtons[row, col].Dispose();
                            }
                        }
                    }
                }

                if (gameEngine.Board == null) return;

                int rows = gameEngine.Board.Rows;
                int cols = gameEngine.Board.Cols;

                // 创建按钮数组
                cellButtons = new Button[rows, cols];

                // 计算网格大小
                int gridWidth = cols * CELL_SIZE;
                int gridHeight = rows * CELL_SIZE;

                // 调整游戏面板大小，确保有足够的空间显示所有按钮
                int panelWidth = gridWidth + GRID_MARGIN * 2;
                int panelHeight = gridHeight + GRID_MARGIN * 2;
                
                // 确保面板大小不小于最小尺寸，但允许根据游戏难度调整
                int minPanelSize = Math.Max(300, Math.Max(rows, cols) * CELL_SIZE / 3); // 动态计算最小尺寸
                panelWidth = Math.Max(panelWidth, minPanelSize);
                panelHeight = Math.Max(panelHeight, minPanelSize);
                
                gamePanel.Size = new Size(panelWidth, panelHeight);

                // 批量创建按钮
                var buttonsToAdd = new List<Button>();
                
                for (int row = 0; row < rows; row++)
                {
                    for (int col = 0; col < cols; col++)
                    {
                                                 Button button = new Button();
                         button.Size = new Size(CELL_SIZE, CELL_SIZE);
                         button.Location = new Point(
                             GRID_MARGIN + col * CELL_SIZE,
                             GRID_MARGIN + row * CELL_SIZE
                         );
                         button.Tag = new Point(row, col);
                         button.Font = new Font("Arial", 8, FontStyle.Bold);
                         
                         // 设置Windows扫雷风格的3D效果
                         button.FlatStyle = FlatStyle.System;
                         button.UseVisualStyleBackColor = false;
                         button.BackColor = Color.FromArgb(192, 192, 192);

                        // 绑定事件
                        button.MouseDown += CellButton_MouseDown;
                        button.MouseUp += CellButton_MouseUp;

                        // 添加到列表以便批量添加
                        buttonsToAdd.Add(button);
                        cellButtons[row, col] = button;
                    }
                }

                // 批量添加所有按钮到面板
                gamePanel.Controls.AddRange(buttonsToAdd.ToArray());

                // 调整窗体大小
                AdjustFormSize();
            }
            finally
            {
                // 恢复界面更新
                gamePanel.ResumeLayout(false);
                this.ResumeLayout(false);
            }
        }

        /// <summary>
        /// 调整窗体大小
        /// </summary>
        private void AdjustFormSize()
        {
            if (gamePanel.Size.Width > 0 && gamePanel.Size.Height > 0)
            {
                // 计算窗体大小，确保游戏区域完全显示
                int formWidth = gamePanel.Size.Width + controlPanel.Size.Width + 24; // 减少间距，只保留必要的边距
                
                // 根据游戏难度设置不同的最小窗体大小
                int minFormWidth, minFormHeight;
                if (gameEngine.Board != null)
                {
                    int rows = gameEngine.Board.Rows;
                    int cols = gameEngine.Board.Cols;
                    
                    // 根据难度动态计算最小窗体大小
                    if (rows <= 9 && cols <= 9) // 初级
                    {
                        minFormWidth = 500;
                        minFormHeight = 400;
                    }
                    else if (rows <= 16 && cols <= 16) // 中级
                    {
                        minFormWidth = 600;
                        minFormHeight = 500;
                    }
                    else // 高级
                    {
                        minFormWidth = 800;
                        minFormHeight = 600;
                    }
                }
                else
                {
                    minFormWidth = 500;
                    minFormHeight = 400;
                }
                
                // 设置最小窗体大小
                this.MinimumSize = new Size(minFormWidth, minFormHeight);
                
                // 计算窗体高度：游戏面板高度 + 控制面板高度 + 边距
                // 控制面板高度根据游戏难度动态调整
                int controlPanelHeight;
                if (gameEngine.Board != null)
                {
                    int rows = gameEngine.Board.Rows;
                    int cols = gameEngine.Board.Cols;
                    
                    if (rows <= 9 && cols <= 9) // 初级
                    {
                        controlPanelHeight = 350; // 较小的控制面板高度
                    }
                    else if (rows <= 16 && cols <= 16) // 中级
                    {
                        controlPanelHeight = 400; // 中等控制面板高度
                    }
                    else // 高级
                    {
                        controlPanelHeight = 450; // 较大的控制面板高度
                    }
                }
                else
                {
                    controlPanelHeight = 350;
                }
                
                int formHeight = Math.Max(gamePanel.Size.Height, controlPanelHeight) + 100; // 增加间距
                
                // 强制调整窗体大小以适应新的游戏难度
                // 确保窗体大小不小于计算出的最小尺寸
                formWidth = Math.Max(formWidth, minFormWidth);
                formHeight = Math.Max(formHeight, minFormHeight);
                
                // 调整控制面板位置和大小
                int controlPanelX = gamePanel.Size.Width + 12; // 紧贴游戏面板右侧，留12像素间距
                controlPanel.Location = new Point(controlPanelX, 11);
                controlPanel.Size = new Size(controlPanel.Width, controlPanelHeight);
                
                this.Size = new Size(formWidth, formHeight);
            }
        }

        /// <summary>
        /// 窗体大小改变事件处理
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            // 当窗体大小改变时，调整游戏面板和控制面板以适应新的窗体大小
            if (gameEngine.Board != null && cellButtons != null)
            {
                // 调整控制面板高度以适应新的窗体高度
                int controlPanelHeight = this.ClientSize.Height - 22; // 减去上下边距
                controlPanel.Size = new Size(controlPanel.Width, controlPanelHeight);
                
                // 计算游戏面板应该的大小
                int availableWidth = this.ClientSize.Width - controlPanel.Width - 24; // 减去控制面板宽度和间距
                int availableHeight = this.ClientSize.Height - 100; // 减去上下边距
                
                // 确保游戏面板不会小于最小尺寸
                int minPanelWidth = gameEngine.Board.Cols * CELL_SIZE + GRID_MARGIN * 2;
                int minPanelHeight = gameEngine.Board.Rows * CELL_SIZE + GRID_MARGIN * 2;
                
                int newPanelWidth = Math.Max(availableWidth, minPanelWidth);
                int newPanelHeight = Math.Max(availableHeight, minPanelHeight);
                
                // 调整游戏面板大小
                gamePanel.Size = new Size(newPanelWidth, newPanelHeight);
            }
        }

        /// <summary>
        /// 更新用户界面
        /// </summary>
        private void UpdateUI()
        {
            if (gameEngine.Board == null) return;

            // 更新地雷计数
            mineCountLabel.Text = $"剩余地雷: {gameEngine.Board.RemainingMines}";

            // 更新游戏时间
            UpdateTimeDisplay();

            // 更新所有方块显示
            UpdateAllCells();

            // 更新演示控制
            UpdateDemoControls();
        }

        /// <summary>
        /// 更新所有方块显示
        /// </summary>
        private void UpdateAllCells()
        {
            if (gameEngine.Board == null || cellButtons == null) return;

            for (int row = 0; row < gameEngine.Board.Rows; row++)
            {
                for (int col = 0; col < gameEngine.Board.Cols; col++)
                {
                    UpdateCellDisplay(row, col);
                }
            }
        }

        /// <summary>
        /// 更新单个方块显示
        /// </summary>
        /// <param name="row">行索引</param>
        /// <param name="col">列索引</param>
        private void UpdateCellDisplay(int row, int col)
        {
            if (cellButtons == null || row < 0 || row >= cellButtons.GetLength(0) || 
                col < 0 || col >= cellButtons.GetLength(1)) return;

            var cell = gameEngine.Board.Cells[row, col];
            var button = cellButtons[row, col];

            // 确定显示文本
            string displayText = "";
            if (cell.IsFlagged)
            {
                displayText = FLAG_CHAR;
            }
            else if (cell.IsRevealed)
            {
                if (cell.AdjacentMineCount > 0)
                {
                    displayText = cell.AdjacentMineCount.ToString();
                }
                else
                {
                    displayText = "";
                }
            }
            else
            {
                displayText = "";
            }

            // 应用样式
            ApplyCellStyle(button, cell.IsRevealed, cell.IsFlagged, cell.AdjacentMineCount, displayText);
        }



        /// <summary>
        /// 创建状态预览按钮
        /// </summary>
        private void CreatePreviewButtons()
        {
            const int previewButtonSize = 20;
            const int buttonsPerRow = 4;
            const int spacing = 2;
            
            // 定义所有状态
            var states = new[]
            {
                new { Name = "未揭开", Text = "", IsRevealed = false, IsFlagged = false, AdjacentMineCount = 0 },
                new { Name = "旗帜", Text = FLAG_CHAR, IsRevealed = false, IsFlagged = true, AdjacentMineCount = 0 },
                new { Name = "数字1", Text = "1", IsRevealed = true, IsFlagged = false, AdjacentMineCount = 1 },
                new { Name = "数字2", Text = "2", IsRevealed = true, IsFlagged = false, AdjacentMineCount = 2 },
                new { Name = "数字3", Text = "3", IsRevealed = true, IsFlagged = false, AdjacentMineCount = 3 },
                new { Name = "数字4", Text = "4", IsRevealed = true, IsFlagged = false, AdjacentMineCount = 4 },
                new { Name = "数字5", Text = "5", IsRevealed = true, IsFlagged = false, AdjacentMineCount = 5 },
                new { Name = "数字6", Text = "6", IsRevealed = true, IsFlagged = false, AdjacentMineCount = 6 },
                new { Name = "地雷", Text = "💣", IsRevealed = true, IsFlagged = false, AdjacentMineCount = 0 }
            };
            
            for (int i = 0; i < states.Length; i++)
            {
                var state = states[i];
                int row = i / buttonsPerRow;
                int col = i % buttonsPerRow;
                
                Button button = new Button();
                button.Size = new Size(previewButtonSize, previewButtonSize);
                button.Location = new Point(
                    spacing + col * (previewButtonSize + spacing),
                    spacing + row * (previewButtonSize + spacing)
                );
                button.Font = new Font("Arial", 8, FontStyle.Bold);
                button.Tag = state;
                
                // 应用状态样式
                ApplyCellStyle(button, state.IsRevealed, state.IsFlagged, state.AdjacentMineCount, state.Text);
                
                previewPanel.Controls.Add(button);
            }
        }
        
        /// <summary>
        /// 初始化虚拟鼠标
        /// </summary>
        private void InitializeVirtualMouse()
        {
            // 加载原始光标图像
            LoadCursorImage();
            
            // 创建虚拟鼠标光标
            virtualMouseCursor = new PictureBox();
            virtualMouseCursor.Size = new Size(32, 32); // 正常鼠标光标大小
            virtualMouseCursor.BackColor = Color.Transparent;
            virtualMouseCursor.Image = CreateMouseCursorImage();
            virtualMouseCursor.Visible = false;
            
            // 创建虚拟鼠标移动定时器
            virtualMouseTimer = new Timer();
            virtualMouseTimer.Interval = 32; // 30 FPS（更慢，更平滑）
            virtualMouseTimer.Tick += VirtualMouseTimer_Tick;
            
            // 将虚拟鼠标添加到游戏面板
            gamePanel.Controls.Add(virtualMouseCursor);
            virtualMouseCursor.BringToFront();
            
            // 初始位置设为游戏面板中心
            virtualMousePosition = new Point(gamePanel.Width / 2, gamePanel.Height / 2);
            virtualMouseCursor.Location = virtualMousePosition;
        }
        
        /// <summary>
        /// 加载光标图像
        /// </summary>
        private void LoadCursorImage()
        {
            try
            {
                string cursorPath = Path.Combine(Application.StartupPath, "images", "cursor.png");
                if (File.Exists(cursorPath))
                {
                    originalCursorImage = Image.FromFile(cursorPath);
                }
                else
                {
                    // 如果找不到文件，创建一个默认的光标图像
                    originalCursorImage = CreateDefaultCursorImage();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载光标图像失败: {ex.Message}");
                originalCursorImage = CreateDefaultCursorImage();
            }
        }
        
        /// <summary>
        /// 创建默认光标图像
        /// </summary>
        /// <returns>默认光标图像</returns>
        private Bitmap CreateDefaultCursorImage()
        {
            Bitmap bitmap = new Bitmap(32, 32);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                
                // 绘制简单的箭头光标
                Point[] arrowPoints = {
                    new Point(2, 2),   // 箭头尖端
                    new Point(8, 8),   // 箭头头部
                    new Point(6, 8),   // 箭头颈部
                    new Point(6, 24),  // 箭头尾部
                    new Point(4, 24),  // 箭头尾部
                    new Point(4, 8),   // 箭头颈部
                    new Point(2, 8)    // 箭头头部
                };
                
                g.FillPolygon(Brushes.Black, arrowPoints);
                g.DrawPolygon(Pens.White, arrowPoints);
            }
            return bitmap;
        }
        
        /// <summary>
        /// 创建鼠标光标图像
        /// </summary>
        /// <returns>鼠标光标图像</returns>
        private Bitmap CreateMouseCursorImage()
        {
            Bitmap bitmap = new Bitmap(32, 32);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                // 设置高质量绘图
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                
                // 绘制原始光标图像（缩放到32x32）
                if (originalCursorImage != null)
                {
                    g.DrawImage(originalCursorImage, 0, 0, 32, 32);
                }
                else
                {
                    // 如果原始图像不存在，绘制默认箭头
                    Point[] arrowPoints = {
                        new Point(2, 2),   // 箭头尖端
                        new Point(8, 8),   // 箭头头部
                        new Point(6, 8),   // 箭头颈部
                        new Point(6, 24),  // 箭头尾部
                        new Point(4, 24),  // 箭头尾部
                        new Point(4, 8),   // 箭头颈部
                        new Point(2, 8)    // 箭头头部
                    };
                    
                    g.FillPolygon(Brushes.Black, arrowPoints);
                    g.DrawPolygon(Pens.White, arrowPoints);
                }
                
                // 根据按钮状态绘制按钮
                if (virtualLeftButtonDown)
                {
                    // 左键按下：绘制绿色按钮在左侧
                    DrawMouseButton(g, 4, 18, Color.LightGreen, Color.Green);
                }
                
                if (virtualRightButtonDown)
                {
                    // 右键按下：绘制红色按钮在右侧
                    DrawMouseButton(g, 20, 18, Color.LightCoral, Color.Red);
                }
            }
            return bitmap;
        }
        
        /// <summary>
        /// 绘制鼠标按钮
        /// </summary>
        /// <param name="g">绘图对象</param>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <param name="fillColor">填充颜色</param>
        /// <param name="borderColor">边框颜色</param>
        private void DrawMouseButton(Graphics g, int x, int y, Color fillColor, Color borderColor)
        {
            // 绘制按钮（小圆点）
            using (SolidBrush brush = new SolidBrush(fillColor))
            using (Pen pen = new Pen(borderColor, 1))
            {
                g.FillEllipse(brush, x, y, 6, 6);
                g.DrawEllipse(pen, x, y, 6, 6);
            }
        }
        
        /// <summary>
        /// 更新虚拟鼠标光标图像
        /// </summary>
        private void UpdateVirtualMouseCursor()
        {
            if (virtualMouseCursor != null && virtualMouseCursor.Visible)
            {
                virtualMouseCursor.Image = CreateMouseCursorImage();
            }
        }
        
        /// <summary>
        /// 设置虚拟鼠标左键状态
        /// </summary>
        /// <param name="isDown">是否按下</param>
        private void SetVirtualLeftButton(bool isDown)
        {
            virtualLeftButtonDown = isDown;
            UpdateVirtualMouseCursor();
        }
        
        /// <summary>
        /// 设置虚拟鼠标右键状态
        /// </summary>
        /// <param name="isDown">是否按下</param>
        private void SetVirtualRightButton(bool isDown)
        {
            virtualRightButtonDown = isDown;
            UpdateVirtualMouseCursor();
        }
        
        /// <summary>
        /// 虚拟鼠标定时器事件
        /// </summary>
        private void VirtualMouseTimer_Tick(object sender, EventArgs e)
        {
            if (!isMoving) return;
            
            // 计算当前位置到目标位置的距离
            int dx = targetPosition.X - virtualMousePosition.X;
            int dy = targetPosition.Y - virtualMousePosition.Y;
            double distance = Math.Sqrt(dx * dx + dy * dy);
            
            if (distance < 2)
            {
                // 到达目标位置
                virtualMousePosition = targetPosition;
                isMoving = false;
                virtualMouseTimer.Stop();
                return;
            }
            
            // 计算移动速度（距离越近速度越慢）
            double speedFactor = Math.Max(0.1, distance / 100.0);
            double moveSpeed = 2 + speedFactor * 5; // 基础速度2，最大速度7（更慢）
            
            // 计算移动步长
            double stepX = (dx / distance) * moveSpeed;
            double stepY = (dy / distance) * moveSpeed;
            
            // 更新位置
            virtualMousePosition.X += (int)stepX;
            virtualMousePosition.Y += (int)stepY;
            
            // 更新虚拟鼠标位置
            virtualMouseCursor.Location = virtualMousePosition;
        }
        
        /// <summary>
        /// 移动虚拟鼠标到指定位置
        /// </summary>
        /// <param name="targetRow">目标行</param>
        /// <param name="targetCol">目标列</param>
        private void MoveVirtualMouseTo(int targetRow, int targetCol)
        {
            if (!isVirtualMouseVisible) return;
            
            // 计算目标位置（方块中心）
            int targetX = GRID_MARGIN + targetCol * CELL_SIZE + CELL_SIZE / 2;
            int targetY = GRID_MARGIN + targetRow * CELL_SIZE + CELL_SIZE / 2;
            
            // 调整位置，使箭头的尖端（2,2）对准目标位置
            targetX -= 2;
            targetY -= 2;
            
            targetPosition = new Point(targetX, targetY);
            isMoving = true;
            virtualMouseTimer.Start();
        }
        
        /// <summary>
        /// 显示虚拟鼠标
        /// </summary>
        private void ShowVirtualMouse()
        {
            isVirtualMouseVisible = true;
            virtualMouseCursor.Visible = true;
            
            // 确保虚拟鼠标在正确的位置并且可见
            if (virtualMouseCursor != null && gamePanel.Controls.Contains(virtualMouseCursor))
            {
                virtualMouseCursor.BringToFront();
                // 设置初始位置为游戏面板中心
                virtualMousePosition = new Point(gamePanel.Width / 2, gamePanel.Height / 2);
                virtualMouseCursor.Location = virtualMousePosition;
            }
        }
        
        /// <summary>
        /// 隐藏虚拟鼠标
        /// </summary>
        private void HideVirtualMouse()
        {
            isVirtualMouseVisible = false;
            virtualMouseCursor.Visible = false;
            isMoving = false;
            virtualMouseTimer.Stop();
        }

        /// <summary>
        /// 应用方块样式
        /// </summary>
        /// <param name="button">按钮</param>
        /// <param name="isRevealed">是否已揭开</param>
        /// <param name="isFlagged">是否标记为旗帜</param>
        /// <param name="adjacentMineCount">周围地雷数量</param>
        /// <param name="text">显示文本</param>
        private void ApplyCellStyle(Button button, bool isRevealed, bool isFlagged, int adjacentMineCount, string text)
        {
            if (isFlagged)
            {
                // 旗帜：使用字符显示
                button.FlatStyle = FlatStyle.System;
                button.UseVisualStyleBackColor = false;
                button.BackColor = Color.FromArgb(192, 192, 192); // 浅灰色背景
                button.Text = text; // 显示旗帜字符
                button.ForeColor = Color.Red; // 旗帜为红色
                button.Image = null; // 清除图片
            }
            else if (isRevealed)
            {
                // 已揭开的方块：扁平化效果
                button.FlatStyle = FlatStyle.Flat;
                button.UseVisualStyleBackColor = false;
                button.BackColor = Color.FromArgb(192, 192, 192); // 浅灰色背景
                button.Image = null; // 清除图片
                button.Text = text;
                
                // 设置数字颜色（Windows扫雷标准颜色）
                if (adjacentMineCount > 0)
                {
                    switch (adjacentMineCount)
                    {
                        case 1: button.ForeColor = Color.FromArgb(0, 0, 255); break;     // 蓝色
                        case 2: button.ForeColor = Color.FromArgb(0, 128, 0); break;     // 绿色
                        case 3: button.ForeColor = Color.FromArgb(255, 0, 0); break;     // 红色
                        case 4: button.ForeColor = Color.FromArgb(0, 0, 128); break;     // 深蓝色
                        case 5: button.ForeColor = Color.FromArgb(128, 0, 0); break;     // 深红色
                        case 6: button.ForeColor = Color.FromArgb(0, 128, 128); break;   // 青色
                        case 7: button.ForeColor = Color.FromArgb(0, 0, 0); break;       // 黑色
                        case 8: button.ForeColor = Color.FromArgb(128, 128, 128); break; // 灰色
                        default: button.ForeColor = Color.Black; break;
                    }
                }
                else
                {
                    button.ForeColor = Color.Black;
                }
            }
            else
            {
                // 未揭开的方块：3D凸起效果
                button.FlatStyle = FlatStyle.System;
                button.UseVisualStyleBackColor = false;
                button.BackColor = Color.FromArgb(192, 192, 192);
                button.Text = text;
                button.ForeColor = Color.Black;
                button.Image = null; // 清除图片
            }
            
            // 设置字体
            if (isRevealed && adjacentMineCount > 0)
            {
                button.Font = new Font("Arial", 8, FontStyle.Bold);
            }
            else
            {
                button.Font = new Font("Arial", 8, FontStyle.Bold);
            }
        }

        /// <summary>
        /// 高亮显示方块（用于演示）
        /// </summary>
        /// <param name="row">行索引</param>
        /// <param name="col">列索引</param>
        /// <param name="highlight">是否高亮</param>
        private void HighlightCell(int row, int col, bool highlight)
        {
            if (cellButtons == null || row < 0 || row >= cellButtons.GetLength(0) || 
                col < 0 || col >= cellButtons.GetLength(1)) return;

            var button = cellButtons[row, col];
            if (highlight)
            {
                // 高亮时使用黄色背景和红色边框
                button.BackColor = Color.Yellow;
                button.FlatStyle = FlatStyle.Flat;
                button.FlatAppearance.BorderColor = Color.Red;
                button.FlatAppearance.BorderSize = 2;
            }
            else
            {
                // 取消高亮时恢复正确的颜色和3D效果
                UpdateCellDisplay(row, col);
            }
        }

        /// <summary>
        /// 更新时间显示
        /// </summary>
        private void UpdateTimeDisplay()
        {
            int seconds = gameEngine.GameTime;
            int minutes = seconds / 60;
            seconds = seconds % 60;
            timeLabel.Text = $"游戏时间: {minutes:D2}:{seconds:D2}";
        }

        /// <summary>
        /// 更新演示控制按钮状态
        /// </summary>
        private void UpdateDemoControls()
        {
            bool demoEnabled = autoDemoCheckBox.Checked;
            bool gameReady = gameEngine.State == GameState.NotStarted || gameEngine.State == GameState.Playing;
            bool demoRunning = autoDemo.IsRunning;
            bool demoPaused = autoDemo.IsPaused;

            startDemoButton.Enabled = demoEnabled && gameReady && !demoRunning;
            pauseDemoButton.Enabled = demoEnabled && demoRunning && !demoPaused;
            stopDemoButton.Enabled = demoEnabled && demoRunning;
            stepDemoButton.Enabled = demoEnabled && gameReady && (!demoRunning || demoPaused);
            demoSpeedComboBox.Enabled = demoEnabled && !demoRunning;

            // 更新按钮文本
            if (demoPaused)
            {
                pauseDemoButton.Text = "继续";
            }
            else
            {
                pauseDemoButton.Text = "暂停";
            }

            // 更新表情按钮
            UpdateFaceButton();
        }

        /// <summary>
        /// 更新表情按钮
        /// </summary>
        private void UpdateFaceButton()
        {
            switch (gameEngine.State)
            {
                case GameState.NotStarted:
                    faceButton.Text = "😊";
                    break;
                case GameState.Playing:
                    faceButton.Text = "😮";
                    break;
                case GameState.Won:
                    faceButton.Text = "😎";
                    break;
                case GameState.Lost:
                    faceButton.Text = "💀";
                    break;
                case GameState.Paused:
                    faceButton.Text = "😴";
                    break;
                default:
                    faceButton.Text = "😊";
                    break;
            }
        }

        #region 事件处理

        /// <summary>
        /// 新游戏按钮点击事件
        /// </summary>
        private void NewGameButton_Click(object sender, EventArgs e)
        {
            StartNewGame();
        }

        /// <summary>
        /// 难度选择改变事件
        /// </summary>
        private void DifficultyComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            StartNewGame();
        }

        /// <summary>
        /// 游戏计时器事件
        /// </summary>
        private void GameTimer_Tick(object sender, EventArgs e)
        {
            UpdateTimeDisplay();
        }

        /// <summary>
        /// 自动演示复选框改变事件
        /// </summary>
        private void AutoDemoCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            UpdateDemoControls();
        }

        /// <summary>
        /// 演示速度改变事件
        /// </summary>
        private void DemoSpeedComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (autoDemo != null)
            {
                autoDemo.Speed = (DemoSpeed)demoSpeedComboBox.SelectedIndex;
            }
        }

        /// <summary>
        /// 开始演示按钮点击事件
        /// </summary>
        private void StartDemoButton_Click(object sender, EventArgs e)
        {
            if (autoDemo != null && !autoDemo.IsRunning)
            {
                autoDemo.StartDemo();
                ShowVirtualMouse();
                UpdateDemoControls();
            }
        }

        /// <summary>
        /// 暂停演示按钮点击事件
        /// </summary>
        private void PauseDemoButton_Click(object sender, EventArgs e)
        {
            if (autoDemo != null)
            {
                if (autoDemo.IsPaused)
                {
                    autoDemo.ResumeDemo();
                }
                else
                {
                    autoDemo.PauseDemo();
                }
                UpdateDemoControls();
            }
        }

        /// <summary>
        /// 停止演示按钮点击事件
        /// </summary>
        private void StopDemoButton_Click(object sender, EventArgs e)
        {
            if (autoDemo != null)
            {
                autoDemo.StopDemo();
                HideVirtualMouse();
                UpdateDemoControls();
            }
        }

        /// <summary>
        /// 单步演示按钮点击事件
        /// </summary>
        private void StepDemoButton_Click(object sender, EventArgs e)
        {
            if (autoDemo != null)
            {
                autoDemo.StepDemo();
            }
        }

        /// <summary>
        /// 统计信息按钮点击事件
        /// </summary>
        private void StatsButton_Click(object sender, EventArgs e)
        {
            string statsSummary = statistics.GetStatsSummary();
            MessageBox.Show(statsSummary, "游戏统计", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 表情按钮点击事件
        /// </summary>
        private void FaceButton_Click(object sender, EventArgs e)
        {
            StartNewGame();
        }

        /// <summary>
        /// 重置统计按钮点击事件
        /// </summary>
        private void ResetStatsButton_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show("确定要重置所有统计信息吗？此操作不可撤销。", 
                "重置统计", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            
            if (result == DialogResult.Yes)
            {
                statistics.ResetStats();
                MessageBox.Show("统计信息已重置。", "重置完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 排行榜按钮点击事件
        /// </summary>
        private void LeaderboardButton_Click(object sender, EventArgs e)
        {
            var leaderboardForm = new LeaderboardForm(leaderboard);
            leaderboardForm.ShowDialog(this);
        }

        /// <summary>
        /// 获取玩家姓名
        /// </summary>
        /// <returns>玩家姓名</returns>
        private string GetPlayerName()
        {
            using (var inputForm = new Form())
            {
                inputForm.Text = "输入姓名";
                inputForm.Size = new Size(300, 150);
                inputForm.StartPosition = FormStartPosition.CenterParent;
                inputForm.FormBorderStyle = FormBorderStyle.FixedDialog;
                inputForm.MaximizeBox = false;
                inputForm.MinimizeBox = false;

                var label = new Label();
                label.Text = "恭喜你进入排行榜！请输入你的姓名：";
                label.Location = new Point(10, 10);
                label.Size = new Size(260, 20);

                var textBox = new TextBox();
                textBox.Location = new Point(10, 35);
                textBox.Size = new Size(260, 20);

                var okButton = new Button();
                okButton.Text = "确定";
                okButton.Location = new Point(110, 70);
                okButton.Size = new Size(60, 25);
                okButton.DialogResult = DialogResult.OK;

                var cancelButton = new Button();
                cancelButton.Text = "取消";
                cancelButton.Location = new Point(180, 70);
                cancelButton.Size = new Size(60, 25);
                cancelButton.DialogResult = DialogResult.Cancel;

                inputForm.Controls.AddRange(new Control[] { label, textBox, okButton, cancelButton });
                inputForm.AcceptButton = okButton;
                inputForm.CancelButton = cancelButton;

                if (inputForm.ShowDialog() == DialogResult.OK)
                {
                    return textBox.Text.Trim();
                }

                return "";
            }
        }

        /// <summary>
        /// 方块按钮鼠标按下事件
        /// </summary>
        private void CellButton_MouseDown(object sender, MouseEventArgs e)
        {
            if (gameEngine.State != GameState.NotStarted && gameEngine.State != GameState.Playing)
                return;

            var button = sender as Button;
            var position = (Point)button.Tag;
            int row = position.X;
            int col = position.Y;
            lastMousePosition = new Point(row, col);

            // 更新鼠标按键状态
            if (e.Button == MouseButtons.Left)
            {
                leftMouseDown = true;
                SetVirtualLeftButton(true);
            }
            else if (e.Button == MouseButtons.Right)
            {
                rightMouseDown = true;
                SetVirtualRightButton(true);
            }

            // 检查是否左右键同时按下
            if (leftMouseDown && rightMouseDown)
            {
                HandleBothMouseButtonsClick(row, col);
                return;
            }

            // 左键点击 - 揭开方块
            if (e.Button == MouseButtons.Left)
            {
                var result = gameEngine.RevealCell(row, col);
                
                if (result == RevealResult.HitMine)
                {
                    // 记录游戏失败
                    statistics.RecordGameLost(gameEngine.Difficulty);
                    statistics.SaveStats();
                    
                    MessageBox.Show("游戏结束！你踩到地雷了！", "游戏结束", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (result == RevealResult.GameWon)
                {
                    // 记录游戏胜利
                    statistics.RecordGameWon(gameEngine.Difficulty, gameEngine.GameTime);
                    statistics.SaveStats();
                    
                    // 检查是否应该进入排行榜
                    if (leaderboard.ShouldEnterLeaderboard(gameEngine.Difficulty, gameEngine.GameTime))
                    {
                        string playerName = GetPlayerName();
                        if (!string.IsNullOrEmpty(playerName))
                        {
                            bool enteredLeaderboard = leaderboard.AddScore(gameEngine.Difficulty, playerName, gameEngine.GameTime);
                            if (enteredLeaderboard)
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒\n你的成绩已进入排行榜！", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                            "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            // 右键点击 - 标记地雷
            else if (e.Button == MouseButtons.Right)
            {
                var flagResult = gameEngine.ToggleFlag(row, col);
                
                // 检查是否通过标记获胜
                if (gameEngine.State == GameState.Won)
                {
                    // 记录游戏胜利
                    statistics.RecordGameWon(gameEngine.Difficulty, gameEngine.GameTime);
                    statistics.SaveStats();
                    
                    // 检查是否应该进入排行榜
                    if (leaderboard.ShouldEnterLeaderboard(gameEngine.Difficulty, gameEngine.GameTime))
                    {
                        string playerName = GetPlayerName();
                        if (!string.IsNullOrEmpty(playerName))
                        {
                            bool enteredLeaderboard = leaderboard.AddScore(gameEngine.Difficulty, playerName, gameEngine.GameTime);
                            if (enteredLeaderboard)
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒\n你的成绩已进入排行榜！", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                            "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        /// <summary>
        /// 方块按钮鼠标释放事件
        /// </summary>
        private void CellButton_MouseUp(object sender, MouseEventArgs e)
        {
            // 更新鼠标按键状态
            if (e.Button == MouseButtons.Left)
            {
                leftMouseDown = false;
                SetVirtualLeftButton(false);
            }
            else if (e.Button == MouseButtons.Right)
            {
                rightMouseDown = false;
                SetVirtualRightButton(false);
            }
        }

        /// <summary>
        /// 处理左右键同时按下的快速展开
        /// </summary>
        /// <param name="row">行索引</param>
        /// <param name="col">列索引</param>
        private void HandleBothMouseButtonsClick(int row, int col)
        {
            var cell = gameEngine.Board.Cells[row, col];
            
            // 只有已揭开的数字方块才能使用快速展开
            if (!cell.IsRevealed || cell.AdjacentMineCount == 0)
                return;

            // 计算周围标记的地雷数量
            int flaggedCount = 0;
            for (int dr = -1; dr <= 1; dr++)
            {
                for (int dc = -1; dc <= 1; dc++)
                {
                    if (dr == 0 && dc == 0) continue;
                    
                    int newRow = row + dr;
                    int newCol = col + dc;
                    
                    if (newRow >= 0 && newRow < gameEngine.Board.Rows &&
                        newCol >= 0 && newCol < gameEngine.Board.Cols)
                    {
                        if (gameEngine.Board.Cells[newRow, newCol].IsFlagged)
                        {
                            flaggedCount++;
                        }
                    }
                }
            }

            // 如果标记数量等于数字，则快速展开周围未标记的方块
            if (flaggedCount == cell.AdjacentMineCount)
            {
                var result = gameEngine.QuickReveal(row, col);
                
                if (result == RevealResult.HitMine)
                {
                    // 记录游戏失败
                    statistics.RecordGameLost(gameEngine.Difficulty);
                    statistics.SaveStats();
                    
                    MessageBox.Show("游戏结束！你踩到地雷了！", "游戏结束", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (result == RevealResult.GameWon)
                {
                    // 记录游戏胜利
                    statistics.RecordGameWon(gameEngine.Difficulty, gameEngine.GameTime);
                    statistics.SaveStats();
                    
                    // 检查是否应该进入排行榜
                    if (leaderboard.ShouldEnterLeaderboard(gameEngine.Difficulty, gameEngine.GameTime))
                    {
                        string playerName = GetPlayerName();
                        if (!string.IsNullOrEmpty(playerName))
                        {
                            bool enteredLeaderboard = leaderboard.AddScore(gameEngine.Difficulty, playerName, gameEngine.GameTime);
                            if (enteredLeaderboard)
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒\n你的成绩已进入排行榜！", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                        else
                        {
                            MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                            "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                // 如果标记数量不等于数字，也执行快速展开（这是Windows扫雷的行为）
                var result = gameEngine.QuickReveal(row, col);
                
                if (result == RevealResult.HitMine)
                {
                    // 记录游戏失败
                    statistics.RecordGameLost(gameEngine.Difficulty);
                    statistics.SaveStats();
                    
                    MessageBox.Show("游戏结束！你踩到地雷了！", "游戏结束", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (result == RevealResult.GameWon)
                {
                    // 记录游戏胜利
                    statistics.RecordGameWon(gameEngine.Difficulty, gameEngine.GameTime);
                    statistics.SaveStats();
                    
                    // 检查是否应该进入排行榜
                    if (leaderboard.ShouldEnterLeaderboard(gameEngine.Difficulty, gameEngine.GameTime))
                    {
                        string playerName = GetPlayerName();
                        if (!string.IsNullOrEmpty(playerName))
                        {
                            bool enteredLeaderboard = leaderboard.AddScore(gameEngine.Difficulty, playerName, gameEngine.GameTime);
                            if (enteredLeaderboard)
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒\n你的成绩已进入排行榜！", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                    "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                        }
                        else
                        {
                            MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                                "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"恭喜！你赢了！用时：{gameEngine.GameTime}秒", 
                            "游戏胜利", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }



        /// <summary>
        /// 游戏状态改变事件处理
        /// </summary>
        private void OnGameStateChanged(object sender, GameStateChangedEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnGameStateChanged(sender, e)));
                return;
            }

            switch (e.NewState)
            {
                case GameState.NotStarted:
                    gameTimer.Stop();
                    break;
                case GameState.Playing:
                    gameTimer.Start();
                    break;
                case GameState.Won:
                case GameState.Lost:
                    gameTimer.Stop();
                    // 停止演示
                    if (autoDemo.IsRunning)
                    {
                        autoDemo.StopDemo();
                        HideVirtualMouse();
                    }
                    break;
            }

            UpdateUI();
        }

        /// <summary>
        /// 方块状态改变事件处理
        /// </summary>
        private void OnCellChanged(object sender, CellChangedEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnCellChanged(sender, e)));
                return;
            }

            UpdateCellDisplay(e.Row, e.Col);
            UpdateUI();
        }

        /// <summary>
        /// 演示操作完成事件处理
        /// </summary>
        private void OnDemoOperationCompleted(object sender, DemoOperationEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnDemoOperationCompleted(sender, e)));
                return;
            }

            // 移动虚拟鼠标到目标位置，然后执行操作
            MoveVirtualMouseToAndExecute(e.Operation.Row, e.Operation.Col, e.Operation);
        }

        /// <summary>
        /// 移动虚拟鼠标到目标位置并执行操作
        /// </summary>
        private void MoveVirtualMouseToAndExecute(int targetRow, int targetCol, DemoOperation operation)
        {
            // 根据操作类型设置虚拟鼠标按钮状态
            switch (operation.Type)
            {
                case OperationType.Reveal:
                    SetVirtualLeftButton(true);
                    break;
                case OperationType.Flag:
                    SetVirtualRightButton(true);
                    break;
                case OperationType.QuickReveal:
                    SetVirtualLeftButton(true);
                    SetVirtualRightButton(true);
                    break;
            }
            
            // 计算目标位置（按钮中心）
            int targetX = GRID_MARGIN + targetCol * CELL_SIZE + CELL_SIZE / 2 - virtualMouseCursor.Width / 2;
            int targetY = GRID_MARGIN + targetRow * CELL_SIZE + CELL_SIZE / 2 - virtualMouseCursor.Height / 2;
            targetPosition = new Point(targetX, targetY);
            isMoving = true;

            // 开始移动虚拟鼠标
            virtualMouseTimer.Start();

            // 使用一个标志来跟踪是否已经执行了操作
            bool operationExecuted = false;
            
            // 监听移动完成事件
            EventHandler moveCompletedHandler = null;
            moveCompletedHandler = (sender, e) =>
            {
                if (!isMoving && !operationExecuted)
                {
                    operationExecuted = true;
                    virtualMouseTimer.Stop();
                    virtualMouseTimer.Tick -= moveCompletedHandler;
                    
                    // 移动完成后执行游戏操作
                    ExecuteGameOperation(operation);
                    
                    // 操作完成后释放按钮
                    Task.Delay(200).ContinueWith(_ =>
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                SetVirtualLeftButton(false);
                                SetVirtualRightButton(false);
                            }));
                        }
                        else
                        {
                            SetVirtualLeftButton(false);
                            SetVirtualRightButton(false);
                        }
                    });
                }
            };
            
            virtualMouseTimer.Tick += moveCompletedHandler;
        }

        /// <summary>
        /// 执行游戏操作
        /// </summary>
        private void ExecuteGameOperation(DemoOperation operation)
        {
            // 执行游戏操作
            switch (operation.Type)
            {
                case OperationType.Reveal:
                    gameEngine.RevealCell(operation.Row, operation.Col);
                    break;
                case OperationType.Flag:
                    gameEngine.ToggleFlag(operation.Row, operation.Col);
                    break;
                case OperationType.QuickReveal:
                    gameEngine.QuickReveal(operation.Row, operation.Col);
                    break;
            }

            // 高亮显示当前操作的方块
            HighlightCell(operation.Row, operation.Col, true);

            // 显示操作提示
            string operationText = GetOperationText(operation.Type);
            string message = $"{operationText}方块 ({operation.Row + 1}, {operation.Col + 1}) - {operation.Reason}";
            
            // 这里可以添加状态栏显示或其他提示方式
            this.Text = $"扫雷游戏 - {message}";

            // 延迟取消高亮
            Task.Delay(300).ContinueWith(_ =>
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(() => HighlightCell(operation.Row, operation.Col, false)));
                }
                else
                {
                    HighlightCell(operation.Row, operation.Col, false);
                }
            });
        }
        
        /// <summary>
        /// 获取操作类型的中文描述
        /// </summary>
        /// <param name="operationType">操作类型</param>
        /// <returns>操作描述</returns>
        private string GetOperationText(OperationType operationType)
        {
            switch (operationType)
            {
                case OperationType.Reveal:
                    return "揭开";
                case OperationType.Flag:
                    return "标记";
                case OperationType.Unflag:
                    return "取消标记";
                case OperationType.QuickReveal:
                    return "快速展开";
                default:
                    return "操作";
            }
        }

        /// <summary>
        /// 演示完成事件处理
        /// </summary>
        private void OnDemoCompleted(object sender, DemoCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnDemoCompleted(sender, e)));
                return;
            }

            this.Text = "扫雷游戏";
            HideVirtualMouse();
            UpdateDemoControls();
            
            // 记录演示使用
            bool success = gameEngine.State == GameState.Won;
            statistics.RecordDemoUsed(success, gameEngine.GameTime);
            statistics.SaveStats();
            
            if (gameEngine.State == GameState.Won)
            {
                MessageBox.Show("自动演示完成！游戏胜利！", "演示完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (gameEngine.State == GameState.Lost)
            {
                MessageBox.Show("自动演示完成！游戏失败！", "演示完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        #endregion
    }
}
